package com.ruizhong.centercontroll;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class IndexActivity  extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);

       SharedPreferences sharedPreferences = getSharedPreferences("singlePageControl", MODE_PRIVATE);
        String centerServerIp = sharedPreferences.getString("centerServerIp", null);
        String commandServerIp = sharedPreferences.getString("commandServerIp", null);
        String loginPwd = sharedPreferences.getString("loginPwd", null);
        EditText passwordInput = findViewById(R.id.passwordInput);
        EditText centerControlServer = findViewById(R.id.central_control_server_ip);
        EditText commandServerIpInput = findViewById(R.id.command_server_ip);
        centerControlServer.setText(centerServerIp);
        commandServerIpInput.setText(commandServerIp);
//        passwordInput.setText(loginPwd);
        Spinner spinner = findViewById(R.id.spinner);
        String[] data = {"简体中文", "繁体中文", "English"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, data);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        String selectedLanguage = sharedPreferences.getString("language", null);
        spinner.setSelection("简体中文".equals(selectedLanguage) ? 0 : "繁体中文".equals(selectedLanguage) ? 1 : 2);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(final AdapterView<?> parent, View view, final int position, long id) {
                String selectedLanguage = (String) parent.getItemAtPosition(position);
                TextView centerControlServerText = findViewById(R.id.centerControlServerText);
                TextView commandServerIpText = findViewById(R.id.commandServerIpText);

                TextView passwordText = findViewById(R.id.passwordInputText);
                Button enter = findViewById(R.id.enter);
                switch (selectedLanguage) {
                    case "简体中文":
                        centerControlServerText.setText("中控服务器IP");
                        commandServerIpText.setText("用户名");
                        passwordText.setText("密码");
                        enter.setText("进入");
                        break;
                    case "繁体中文":
                        centerControlServerText.setText("中控服務器IP");
                        commandServerIpText.setText("用戶名");
                        passwordText.setText("密码");
                        enter.setText("進入");
                        break;
                    case "English":
                        centerControlServerText.setText("Central Control Server IP");
                        commandServerIpText.setText("Account");
                        passwordText.setText("Password");
                        enter.setText("enter");
                        break;
                }
                SharedPreferences sharedPreferences = getSharedPreferences("singlePageControl", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("language", selectedLanguage);
                editor.apply();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    public void enterServer(View view){
        EditText centerServerIp = findViewById(R.id.central_control_server_ip);
        Editable centerServerIpText = centerServerIp.getText();
        Intent intent = new Intent(IndexActivity.this, SeverActivity.class);
        intent.putExtra("centerServerIp", centerServerIpText.toString());
        startActivity(intent);
    }

    public void enterMain(View view) {
        EditText password = findViewById(R.id.passwordInput);
        String pwd = password.getText().toString();
        EditText centerServerIp = findViewById(R.id.central_control_server_ip);
        EditText commandServerIp = findViewById(R.id.command_server_ip);
        Editable centerServerIpText = centerServerIp.getText();
        Editable commandServerIpText = commandServerIp.getText();
        String account = commandServerIp.getText().toString();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String res = checkPwd(centerServerIpText.toString(),account, pwd);
                if (res != null) {
                    SharedPreferences sharedPreferences = getSharedPreferences("singlePageControl", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("centerServerIp", centerServerIpText.toString());
                    editor.putString("commandServerIp", commandServerIpText.toString());
                    editor.putString("loginPwd", pwd);
                    editor.apply();
                    Intent intent = new Intent(IndexActivity.this, MainActivity.class);
                    intent.putExtra("centerServerIp", centerServerIpText.toString());
                    intent.putExtra("token", res);
                    startActivity(intent);
                }
            }
        }).start();

    }

    private String checkPwd(String ip, String account, String pwd) {
        String requestUrl = "http://" + ip + ":8094/user/api/login";
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            String jsonInputString = "{\"userName\":\""+account+"\", \"password\":\"" + pwd + "\"}";
            try(OutputStream os = connection.getOutputStream()){
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input,0,input.length);
            }
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                Gson gson = new Gson();
                Map map = gson.fromJson(response.toString(), Map.class);
                return (String) map.get("data");
            } else {
                System.out.println("GET request not worked. Response Code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
